package com.sinder.campus_prophet.core.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.TaskExecutor;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author xieyingde
 * @date 2021/6/15
 * 线程池配置
 */
@Configuration
@EnableAsync // 开启异步
public class ThreadPoolConfig {
    @Bean("taskExecutor")
    public TaskExecutor taskExecutor() {
        // 创建一个线程池
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        // 设置核心线程数
        executor.setCorePoolSize(5);
        // 设置最大线程数
        executor.setMaxPoolSize(5);
        // 设置队列容量
        executor.setQueueCapacity(3);
        // 设置线程活跃时间(秒)
        executor.setKeepAliveSeconds(3000);
        // 设置线程默认名称
        executor.setThreadNamePrefix("data-thread-");
        // 设置拒绝策略(四大拒绝策略)rejection-policy：
        // 当pool已经达到max size时，如何处理新任务 CALLER_RUNS：不在新线程中执行任务，而是有调用者所在的线程来执行
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        // 等待所有任务结束后再关闭线程池
        executor.setWaitForTasksToCompleteOnShutdown(true);
        return executor;
    }
}
